document.addEventListener('DOMContentLoaded', async function() {
    const startButton = document.getElementById('startButton');
    const stopButton = document.getElementById('stopButton');
    const refreshButton = document.getElementById('refreshPoints');
    const statusDiv = document.getElementById('status');
    let isRefreshing = false;
    
    // 修改格式化时间函数
    function formatTime(timestamp) {
        if (!timestamp) return '未知时间';
        try {
            const date = new Date(timestamp);
            if (isNaN(date.getTime())) return '无效时间';
            
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');
            const seconds = date.getSeconds().toString().padStart(2, '0');
            return `${hours}:${minutes}:${seconds}`;
        } catch (error) {
            console.error('时间格式化错误:', error);
            return '时间格式错误';
        }
    }
    
    // 修改显示/隐藏刷新状态的函数
    function toggleRefreshStatus(show) {
        const refreshButton = document.getElementById('refreshPoints');
        if (show) {
            refreshButton.classList.add('refreshing');
            refreshButton.disabled = true;
        } else {
            refreshButton.classList.remove('refreshing');
            refreshButton.disabled = false;
        }
        isRefreshing = show;
    }
    
    // 获取并显示积分信息
    async function updateRewardsInfo(forceUpdate = false) {
        if (forceUpdate) {
            toggleRefreshStatus(true);
        }
        
        chrome.runtime.sendMessage({action: "getRewardsInfo", forceUpdate}, function(response) {
            if (response.success) {
                document.getElementById('totalPoints').textContent = response.totalPoints;
                document.getElementById('dailyPoints').textContent = response.dailyPoints;
                document.getElementById('pcPoints').textContent = response.pcSearchPoints;
                document.getElementById('updateTime').textContent = formatTime(response.lastUpdateTime);
                
                // 更新等级显示
                const levelBadge = document.getElementById('levelBadge');
                levelBadge.textContent = response.level;
            } else {
                // 只在获取失败且不是使用缓存数据时清空显示
                if (forceUpdate) {
                    document.getElementById('totalPoints').textContent = '获取失败';
                    document.getElementById('dailyPoints').textContent = '获取失败';
                    document.getElementById('pcPoints').textContent = '获取失败';
                    document.getElementById('updateTime').textContent = '获取失败';
                }
                
                // 显示错误信息
                const errorMessage = `获取失败: ${response.error || '未知错误'}`;
                document.getElementById('status').innerHTML = 
                    `<div class="error-message">${errorMessage}</div>`;
            }
            
            if (forceUpdate) {
                toggleRefreshStatus(false);
            }
        });
    }
    
    // 获取当前状态
    chrome.runtime.sendMessage({action: "getStatus"}, function(response) {
        updateUI(response);
    });
    
    function updateSearchWordsList(searchWords, currentCount) {
        const container = document.getElementById('searchWordsList');
        if (!container) return;

        container.innerHTML = '';
        
        searchWords.forEach((word, index) => {
            const item = document.createElement('div');
            item.className = 'search-word-item';
            if (index === currentCount) {
                item.classList.add('active');
            } else if (index < currentCount) {
                item.classList.add('completed');
            }
            
            // 创建超链接
            const link = document.createElement('a');
            link.href = `https://www.bing.com/search?q=${encodeURIComponent(word)}`;
            link.target = '_blank';
            link.rel = 'noopener noreferrer';
            link.textContent = word;
            link.style.textDecoration = 'none';
            link.style.color = 'inherit';
            link.style.display = 'block';
            link.style.padding = '4px 8px';
            link.style.borderRadius = '4px';
            link.style.transition = 'background-color 0.2s';
            
            // 添加悬停效果
            link.addEventListener('mouseenter', function() {
                this.style.backgroundColor = 'rgba(0, 123, 255, 0.1)';
            });
            link.addEventListener('mouseleave', function() {
                this.style.backgroundColor = 'transparent';
            });
            
            // 添加点击事件处理
            link.addEventListener('click', function(e) {
                e.preventDefault();
                // 在新标签页中打开Bing搜索
                chrome.tabs.create({
                    url: this.href,
                    active: true
                });
            });
            
            item.appendChild(link);
            container.appendChild(item);
        });

        // 移除自动滚动功能，让用户手动控制滚动
    }
    
    // 修改现有的 updateUI 函数
    function updateUI(response) {
        // 更新按钮状态
        startButton.disabled = response.isSearching;
        stopButton.disabled = !response.isSearching;
        
        // 更新状态文本
        if (response.isSearching) {
            const searchProgress = `正在执行第 ${response.currentCount + 1}/${response.maxCount} 次搜索`;
            const keyword = response.currentKeyword ? 
                `<br><span style="font-size: 11px; color: #666;">关键词：${response.currentKeyword}</span>` : '';
            statusDiv.innerHTML = `${searchProgress}`;
            
            // 确保搜索词列表容器可见
            const container = document.getElementById('searchWordsList');
            if (container) {
                container.style.display = 'block';
            }
        } else {
            statusDiv.textContent = response.currentCount >= response.maxCount ? 
                '搜索任务完成！' : '等待开始搜索...';
        }
        
        // 添加搜索词列表更新
        if (response.isSearching) {
            chrome.runtime.sendMessage({action: "getSearchWords"}, function(wordsResponse) {
                if (wordsResponse && wordsResponse.searchWords) {
                    updateSearchWordsList(wordsResponse.searchWords, wordsResponse.currentCount);
                }
            });
        }
    }
    
    // 初始化按钮状态
    stopButton.disabled = true;  // 初始状态下停止按钮不可用
    
    startButton.addEventListener('click', function() {
        chrome.runtime.sendMessage({action: "startSearch"}, function(response) {
            if (response.status === "started") {
                startButton.disabled = true;
                stopButton.disabled = false;
                statusDiv.textContent = "搜索已开始...";
                
                // 立即获取并显示搜索词列表
                chrome.runtime.sendMessage({action: "getSearchWords"}, function(wordsResponse) {
                    if (wordsResponse && wordsResponse.searchWords) {
                        const container = document.getElementById('searchWordsList');
                        if (container) {
                            container.style.display = 'block';  // 确保列表可见
                            updateSearchWordsList(wordsResponse.searchWords, 0);  // 从第一个词开始
                        }
                    }
                });
            } else if (response.status === "rejected") {
                if (response.reason.includes("已有搜索任务")) {
                    statusDiv.textContent = "请稍等片刻再试...";
                    setTimeout(() => {
                        chrome.runtime.sendMessage({action: "startSearch"});
                    }, 3000);
                } else {
                    statusDiv.textContent = response.reason || "无法开始搜索";
                }
            }
        });
    });
    
    stopButton.addEventListener('click', function() {
        chrome.runtime.sendMessage({action: "stopSearch"}, function(response) {
            if (response.status === "stopped") {
                startButton.disabled = false;
                stopButton.disabled = true;
                statusDiv.textContent = "搜索已停止";
                
                // 隐藏搜索词列表容器
                const container = document.getElementById('searchWordsList');
                if (container) {
                    container.style.display = 'none';
                }
            }
        });
    });
    
    refreshButton.addEventListener('click', function() {
        if (!isRefreshing) {
            updateRewardsInfo(true); // 强制更新
        }
    });
    
    // 初始加载积分信息
    updateRewardsInfo();
    
    // 定期更新状态，但不强制更新积分信息
    setInterval(() => {
        if (!isRefreshing) {
            chrome.runtime.sendMessage({action: "getStatus"}, function(response) {
                updateUI(response);
            });
            updateRewardsInfo(false); // 使用缓存的数据
        }
    }, 30000);
    
    // 在获取状态的函数中调用更新搜索词列表
    function updateStatus() {
        chrome.runtime.sendMessage({ action: "getStatus" }, function(response) {
            // 现有的状态更新代码...

            // 获取并更新搜索词列表
            chrome.runtime.sendMessage({ action: "getSearchWords" }, function(wordsResponse) {
                if (wordsResponse && wordsResponse.searchWords) {
                    updateSearchWordsList(wordsResponse.searchWords, wordsResponse.currentCount);
                }
            });
        });
    }
    
    // 确保在页面加载时和定时更新时都调用 updateStatus
    updateStatus();
    // 每秒更新一次状态和搜索词列表
    setInterval(updateStatus, 1000);
}); 